--[[
脚本名称: openwrt_github_hosts.lua
脚本描述: 用于 openwrt 自动更新 github 的 hosts 文件，
		可以手动 lua /path/to/openwrt_github_hosts.lua，
		或者添加 crontab 定时任务自动执行。
作者: crazyevent
日期: 2025-07-22
]]--

-- 读取文件每一行
local function read_lines(filename)
    local lines = {}
    local file, err = io.open(filename, "r")
    if not file then
        error("File not found: " .. err)
        return lines
    end
    
    local i = 0
    for line in file:lines() do
        i = i + 1
        lines[i] = line
    end
    file:close()
    
    return lines
end

-- 创建新 hosts 临时文件
local function update_hosts(src_file, old_file, modify_file)
    -- 创建或覆盖一个新文件用于写入修改后的内容
    local new_file, err = io.open(modify_file, "w")
    if not new_file then
        error("File create failed: " .. err)
        return 0
    end
    
    -- 逐行读取并替换字符串
    local src_lines = read_lines(src_file)
    local old_lines = read_lines(old_file)
    local isStart = false
    local index = 0
    for _, line in ipairs(old_lines) do
        while true do
            local pos = string.find(line, "(.*)start(.*)")
            if pos then
                print("Insert position found: " .. pos)
                isStart = true
            end
            if not isStart then
                new_file:write(line .. "\n")
                print('Skip ' .. line)
                break
            end
            index = index + 1
            -- 替换字符串
            local new_line = src_lines[index]
            new_file:write(new_line .. "\n")
            print("Add " .. new_line)
            break
        end
    end

    -- 如果没有找到起始标记，就直接把 src 内容附加到 new file 后面
    if not isStart then
        for _, line in ipairs(src_lines) do
            index = index + 1
            new_file:write(line .. "\n")
            print("Add " .. line)
        end
    end
    
    -- 关闭文件
    new_file:close()
	return index
end

local function do_update()
    os.execute("rm -rf /tmp/tmp/hosts")
    if os.execute("wget -P /tmp/tmp/ https://gitee.com/if-the-wind/github-hosts/raw/main/hosts") == 0 then
        local ret = update_hosts("/tmp/tmp/hosts", "/etc/hosts", "/tmp/tmp/hosts.new")
        if (os.execute("rm -rf /tmp/tmp/hosts") == 0
           and os.execute("cp /etc/hosts /etc/hosts.bak") == 0
           and os.execute("mv /tmp/tmp/hosts.new /etc/hosts") == 0
           and os.execute("/etc/init.d/dnsmasq restart") == 0) then
            print('Update ' .. tostring(ret) .. ' lines')
        end
    end
end

do_update()

